package com.speechb.modules.system.admin.service.impl;

import com.speechb.modules.system.admin.entity.SysMenu;
import com.speechb.modules.system.admin.mapper.SysMenuMapper;
import com.speechb.modules.system.admin.service.ISysMenuService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author llj
 * @since 2019-10-03
 */
@Service
public class SysMenuServiceImpl extends ServiceImpl<SysMenuMapper, SysMenu> implements ISysMenuService {
   @Autowired
   SysMenuMapper sysMenuMapper;
    @Override
    public List<SysMenu> menus(String text) {
        List<SysMenu> menus = sysMenuMapper.menus(text);
        return convertMenus(menus,0);
    }

    @Override
    public List<SysMenu> findListOfAdmin(String order, String search) {
        return sysMenuMapper.findListOfAdmin(order, search);
    }

    @Override
    public List<SysMenu> searchSelect(String search) {
        return sysMenuMapper.searchSelect(search);
    }

    @Override
    public SysMenu findSortingByParentId(int parentId) {
        return sysMenuMapper.findSortingByParentId(parentId);
    }

    @Override
    public int add(SysMenu sysMenu) {
        return sysMenuMapper.insert(sysMenu);
    }

    @Override
    public int updateSysMenu(int id, String key_name, String content) {
        return sysMenuMapper.updateSysMenu(id, key_name, content);
    }

    private List<SysMenu> convertMenus(List<SysMenu> menus,int parentId) {
        SysMenu sysMenu;
        List<SysMenu> parentMenu = null;
        for (int i=0,size = menus.size();i<size;i++) {
           sysMenu = menus.get(i);
            if(sysMenu.getParent_id() == parentId ) {
                if(sysMenu.getId() == 10010) {
                   sysMenu.setIsHeader(true);
                }
                if(Objects.isNull(parentMenu)) {
                    parentMenu = new ArrayList<>(menus.size());
                }
                parentMenu.add(sysMenu);
                sysMenu.setChildren(convertMenus(menus,sysMenu.getId()));
            }
        }
        return parentMenu;
    }
}
